import json
import time
from datetime import datetime
from typing import Dict, Any, List, Optional
import os

class ModelLogger:
    def __init__(self, log_dir: str = "logs/model_calls"):
        """初始化模型日志记录器
        
        Args:
            log_dir: 日志文件存储目录
        """
        self.log_dir = log_dir
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
            
    def _get_log_file_path(self) -> str:
        """获取当天的日志文件路径"""
        today = datetime.now().strftime("%Y-%m-%d")
        return os.path.join(self.log_dir, f"model_calls_{today}.jsonl")
        
    def log_model_call(self,
                      call_type: str,
                      request: Dict[str, Any],
                      response: Optional[str] = None,
                      error: Optional[str] = None,
                      duration: Optional[float] = None) -> None:
        """记录模型调用日志
        
        Args:
            call_type: 调用类型，如 'chat' 或 'generate'
            request: 请求参数
            response: 模型响应
            error: 错误信息
            duration: 调用持续时间(秒)
        """
        log_entry = {
            "timestamp": datetime.now().isoformat(),
            "type": call_type,
            "request": request,
            "response": response,
            "error": error,
            "duration": duration
        }
        
        self._write_log(log_entry)
        
    def _write_log(self, log_entry: Dict[str, Any]) -> None:
        """写入日志到文件
        
        Args:
            log_entry: 日志条目
        """
        log_file = self._get_log_file_path()
        try:
            with open(log_file, "a", encoding="utf-8") as f:
                f.write(json.dumps(log_entry, ensure_ascii=False) + "\n")
        except Exception as e:
            print(f"写入日志失败: {str(e)}") 